var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {
        title: 'Express'
    });
});

//引入
const AlipaySdk = require("alipay-sdk");

router.post("/alipay", async (req, res) => {
    // 1-配置信息
    // 实例化客户端  商家信息
    const alipaySdk = new AlipaySdk({
        // 设置应用 ID
        appId: '2021000146673469',
        // 设置应用私钥
        privateKey: "MIIEpAIBAAKCAQEAwvg8kZ6/B0NbUMl1vMbM5e9vB9Lzi7jAy1zyeYTl7SFuIICdB6h+xDQsJJxqoXrSNh/s2oZkuM1wwNw1qgbNKyHMmQAdQINPXGr2CvV9cA9RCFoHEo7VQnl4k/kGh3QXm2t4IEl6AbhAxCHrRPcnZZo/+KodTiOA0x+AUXMsvAiybHBGDAgNzPevQUZPmP1W6VeQ9SDryw161lVbFnhfk1tXaPWrjmdWju+e4730H05Ek7i/ksSCGQfM2zagCEfsypHKoWyApcNr3CpQBp2Av/UPfSyN571va7ECtY0r4FgVyQTfaCKYQ+8zrBTaGm2voOPhd4TDR5WJCp00IKZh9QIDAQABAoIBAQCOrQft7ISQtRri8LqHLdgNv/y5dgchzU7QwzDx+m4j7N3hTR0c2JID1MYk+I4To4SndQ9oDwcwMa78g2mGBjooATDvGiVN64ms8N0iwelMkvjSqscYLowjfC7f4lGD2FHaO3gJ8JsnHQXQQZ4gttkOwiVkPGD7qIGCfj/x2t32rwH/EYI5hyGxn85MzAZ/rx3tfSybI5gCwG5LbqQtgCiYEHEwWv2rchdg+X+RRdU/KjKiUDbRXcLUiIHjfBASdOWGIM6gWpaaHr+mtX/isqr8t/bG2HPFy2rZYszspYtPV8nlhiDWeky7HLmoI/t4JbfjBG2eJoXgcNu1At0xBApBAoGBAPbVawwyfTfqgi1jfv8Fm1Ain/6lRVF/zYHiXg/ceXcAu5bsQYkEFrNES7lK/14Rp9zXGlqTHXde5fNjygq+z//rYIn6lqPNzGIQYSIus2JtCIRUcgx+Lbxq49vtf7xg3klgH3wgFOdZQLOFkOKGu2vUipSh4K8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vfQ3Vpfs+DZjqIW8KNAvYBtaHmB6vLv93xw1Eyu4Jo/SvYZIH3SFCQIDAQAB",
        gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do", //支付宝网关
    });

    try {
        // pc端支付 alipay.trade.page.pay
        // H5端支付 alipay.trade.wap.pay
        const result = await alipaySdk.pageExec('alipay.trade.wap.pay', {
            returnUrl: 'echioh://pay/result',
            bizContent: {
                out_trade_no: Date.now(), //订单编号 一个订单号只能支付一次 不能重复支付
                product_code: "FAST_INSTANT_TRADE_PAY",
                subject: "小米手机",
                body: "详情数据",
                total_amount: "10.01"
            }
        });

        // 修改数据库的信息  将你们的订单信息存储起来
        res.json({
            code: 200,
            data: result,
            message: '支付链接生成成功'
        });
    } catch (error) {
        console.error('支付宝支付创建失败:', error);
        res.status(500).json({
            code: 500,
            message: '支付创建失败',
            error: error.message
        });
    }
});

module.exports = router;